package com.lt.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lt.crm.mapper.SysRightMapper;
import com.lt.crm.mapper.SysRoleRightMapper;
import com.lt.crm.mapper.SysUserMapper;
import com.lt.crm.pojo.SysRight;
import com.lt.crm.pojo.SysRole;
import com.lt.crm.pojo.SysRoleRight;
import com.lt.crm.service.SysRoleService;
import com.lt.crm.mapper.SysRoleMapper;
import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
* @author Administrator
* @description 针对表【sys_role】的数据库操作Service实现
* @createDate 2024-06-18 16:58:48
*/
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole>
    implements SysRoleService{


    @Resource
    SysRoleMapper sysRoleMapper;

    @Resource
    SysRightMapper sysRightMapper;

    @Resource
    SysRoleRightMapper sysRoleRightMapper;
    @Autowired
    private SysUserMapper sysUserMapper;

    //根据角色查询权限
    @Override
    public List<SysRight> findRightsByRole(SysRole role) {

        return sysRightMapper.findRightsByRole(role.getRoleId());
    }

    @Override
    public Page<SysRole> findRole(String roleName, Page<SysRole> page) {
        return sysRoleMapper.findRole(roleName,page);
    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    public void deleteRole(Long id) throws JsonProcessingException {
        //查询两个表的记录
        SysRole role = sysRoleMapper.selectById(id);
        QueryWrapper<SysRoleRight> wrapper = new QueryWrapper<>();
        wrapper.eq("rf_role_id", id);
        List<SysRoleRight> sysRoleRight =sysRoleRightMapper.selectList(wrapper);

        // 将用户数据转换为JSON字符串并存储在Redis中
        String roleJson = new ObjectMapper().writeValueAsString(role);
        redisTemplate.opsForValue().set("deletedRoleData:" + id, roleJson);
        String roleRightJson = new ObjectMapper().writeValueAsString(sysRoleRight);
        redisTemplate.opsForValue().set("deletedRoleRightData:" + id, roleRightJson);

        // 设置过期时间（可选）
        redisTemplate.expire("deletedRoleData:" + id, 1, TimeUnit.DAYS);
        redisTemplate.expire("deletedRoleRightData:" + id, 1, TimeUnit.DAYS);

        // 从MySQL中删除用户
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("rf_role_id", id);

        sysRoleRightMapper.delete(queryWrapper);
        sysUserMapper.deletebyusrRoleId(Integer.valueOf(Math.toIntExact(id)));
        sysRoleMapper.deleteById(id);

    }

    public void deleteRoleCache(Long id) throws JsonProcessingException {
        // 从Redis中获取已删除的角色数据
        String roleJson = redisTemplate.opsForValue().get("deletedRoleData:" + id);
        if (roleJson != null) {
            try {
                SysRole role = new ObjectMapper().readValue(roleJson, SysRole.class);
                // 保存到MySQL中的SysRole表
                // 从Redis中获取已删除的角色权限数据
                String roleRightJson = redisTemplate.opsForValue().get("deletedRoleRightData:" + id);
                if (roleRightJson != null) {
                    List<SysRoleRight> sysRoleRightList = new ObjectMapper().readValue(roleRightJson, new TypeReference<List<SysRoleRight>>(){});
                    // 遍历列表并保存到MySQL中的SysRoleRight表
                    for (SysRoleRight sysRoleRight : sysRoleRightList) {
                        sysRoleRight.setRfRoleId(role.getRoleId()); // 确保角色ID与恢复的角色匹配
                    }
                }
                // 从Redis中删除已恢复的数据
                redisTemplate.delete("deletedRoleData:" + id);
                redisTemplate.delete("deletedRoleRightData:" + id);

            } catch (IOException e) {
                // 处理反序列化异常
                e.printStackTrace();
                throw new RuntimeException("Failed to restore role from Redis", e);
            }
        } else {
            throw new RuntimeException("Role data not found in Redis");
        }

    }


    public void restoreRole(Long id) {
        // 从Redis中获取已删除的角色数据
        String roleJson = redisTemplate.opsForValue().get("deletedRoleData:" + id);
        if (roleJson != null) {
            try {
                SysRole role = new ObjectMapper().readValue(roleJson, SysRole.class);
                // 保存到MySQL中的SysRole表
                sysRoleMapper.insert(role); // 注意：这里假设id是自增的，如果不是，需要处理id的问题
                // 从Redis中获取已删除的角色权限数据
                String roleRightJson = redisTemplate.opsForValue().get("deletedRoleRightData:" + id);
                if (roleRightJson != null) {
                    List<SysRoleRight> sysRoleRightList = new ObjectMapper().readValue(roleRightJson, new TypeReference<List<SysRoleRight>>(){});
                    // 遍历列表并保存到MySQL中的SysRoleRight表
                    for (SysRoleRight sysRoleRight : sysRoleRightList) {
                        sysRoleRight.setRfRoleId(role.getRoleId()); // 确保角色ID与恢复的角色匹配
                        sysRoleRightMapper.insert(sysRoleRight);
                    }
                }


                // 从Redis中删除已恢复的数据
                redisTemplate.delete("deletedRoleData:" + id);
                redisTemplate.delete("deletedRoleRightData:" + id);

            } catch (IOException e) {
                // 处理反序列化异常
                e.printStackTrace();
                throw new RuntimeException("Failed to restore role from Redis", e);
            }
        } else {
            throw new RuntimeException("Role data not found in Redis");
        }
    }
}




